package pers.zw.web.controller;

import pers.zw.domain.User;
import pers.zw.service.IUserService;
import pers.zw.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/Servlet/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("userName");
        String userPwd = req.getParameter("userPwd");

        IUserService service = new UserServiceImpl();
        User user = service.loginUser(userName, userPwd);

        //登陆失败
        if (user == null) {
            String message = String.format(
                    "用户名密码有误！！2秒后跳转到登录页面 <meta http-equiv='refresh' content='2;url=%s'",
                    req.getContextPath() + "/Servlet/LoginUIServlet"
            );
            req.setAttribute("message", message);
            req.getRequestDispatcher("/message.jsp").forward(req, resp);
            return;
        }

        //登陆成功
        req.getSession().setAttribute("user", user);
        String message = String.format(
                "恭喜：%s, 登陆成功！3秒后跳到首页<meta http-equiv='refresh' content='3;url=%s'",
                user.getUserName(),
                req.getContextPath()+"/index.jsp"
        );
        req.setAttribute("message", message);
        req.getRequestDispatcher("/message.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
